﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Threading.Tasks;
using SqlSugar;

namespace TestORM1.Model
{
    public class FreeSqlHelper
    {
        private static readonly string connectionString =
            ConfigurationManager.ConnectionStrings["Default"].ConnectionString;

        static IFreeSql fsql = new FreeSql.FreeSqlBuilder()
            .UseConnectionString(FreeSql.DataType.SqlServer, connectionString)
            .UseAutoSyncStructure(true) //自动同步实体结构到数据库
            .Build(); //请务必定义成 Singleton 单例模式

        public static void Insert(Blog input)
        {
            fsql.Insert<Blog>()
                .AppendData(input)
                .ExecuteIdentity();
        }
        public static void Insert(List<Blog> list)
        {
            fsql.Insert<Blog>()
                .AppendData(list)
                .ExecuteIdentity();
        }

        public static void Update(Blog input)
        {
            fsql.Update<Blog>()
                .Set(b => b.Title, "http://sample2222.com")
                .Where(b => b.Title == "http://sample.com")
                .ExecuteAffrows();
        }

        public static void Delete(int id)
        {
            fsql.Delete<Blog>()
                .Where(b => b.Id == id)
                .ExecuteAffrows();
        }
        public static Blog Get(int id)
        {
            return fsql.Select<Blog>()
                  .Where(a => a.Id == id)
                  .ToOne();
        }
        /// <summary>
        /// ID 倒叙
        /// </summary>
        /// <param name="take"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public static List<Blog> GetListOrberId(int take, int size = 100)
        {
            var total = 0l;
            return fsql.Select<Blog>()
                .Where(m => m.CTime < DateTime.Now)
                .OrderByDescending(m => m.Id)
                .Count(out total) //总记录数量
                .Page(take / size, size).ToList();
        }
        /// <summary>
        /// 创建时间倒叙
        /// </summary>
        /// <param name="take"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public static List<Blog> GetListOrberTime(int take, int size = 100)
        {
            var total=0l;
            return fsql.Select<Blog>()
                .Where(m => m.CTime < DateTime.Now)
                .OrderByDescending(m => m.CTime)
                .Count(out total) //总记录数量
                .Page(take/size,size).ToList();
        }
    }
}